package cn.itcast.service.impl;

import cn.itcast.mapper.OrderLogMapper;
import cn.itcast.mapper.OrderMapper;
import cn.itcast.pojo.Order;
import cn.itcast.pojo.OrderLog;
import cn.itcast.service.OrderService;
import cn.itcast.util.IdWorker;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {
    
    @Autowired
    private OrderMapper orderMapper;
    public static final int ORDER_TIME_OUT = 10;
    public static final int PAGE = 1;
    public static final int SIZE = 2;
    
    @Override
    public List<Order> findOrderTimeOut(int item, int sharingCount) {
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        //订单状态0，支付状态0，下单时间超过10分钟 ，id % sharingCount = item
        criteria.andEqualTo("orderStatus", "0");
        criteria.andEqualTo("payStatus", "0");
        Date date = DateUtils.addMinutes(new Date(), -ORDER_TIME_OUT);
        criteria.andLessThan("createTime", date);
        criteria.andCondition("id % " + sharingCount + "=" + item);
        
        //设置分页参数
        PageHelper.startPage(PAGE, SIZE);
        List<Order> orderList = orderMapper.selectByExample(example);//条件查询
        return orderList;
    }
    
    @Override
    public void updateStatus(Order order, String status) {
        Long id = order.getId();
        String oldStatus = order.getOrderStatus();
        
        order.setOrderStatus(status);
        order.setUpdateTime(new Date());
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id", id);
        criteria.andEqualTo("orderStatus", oldStatus);
        orderMapper.updateByExampleSelective(order, example); //根据条件进行修改
    }
    
    @Autowired
    private OrderLogMapper orderLogMapper;
    
    @Override
    public void countOrder(Date startDate, Date endDate) {
        Map<String, Object> map = orderMapper.countOrder(startDate, endDate);
        BigDecimal totalMoneys = (BigDecimal) map.get("totalMoneys");
        BigDecimal totalNums = (BigDecimal) map.get("totalNums");
        
        OrderLog orderLog = new OrderLog();
        IdWorker idWorker = new IdWorker();
        orderLog.setId(idWorker.nextId());
        orderLog.setStartDate(startDate);
        orderLog.setEndDate(endDate);
        orderLog.setTotalMoney(totalMoneys);
        orderLog.setTotalNum(totalNums.intValue());
        orderLogMapper.insert(orderLog);
    }
    
}
